<template>
  <div class="common-page-container">
    <a-card :bordered="false" class="common-content-card">
      <!-- 搜索区域 -->
      <BaseSearch
        v-model="queryParams" 
        :showButtons=false
        :form-items="searchItems"
        :date-range="dateRange"
        @search="handleSearch"
        @reset="handleReset"
        @date-change="handleDateRangeChange"
      />
      
      <!-- 操作按钮区域 -->
      <Operations 
        :selected-count="selectedCount"
        :left-buttons="useLeftButtons(selectedCount)"
        :right-buttons="useRightButtons()"
        @add="handleAdd"
        @batch-delete="handleBatchDelete"
        @export="handleExport"
        @refresh="fetchUserList"
        @search="handleSearch"
        @reset="handleReset"
      />

      <BaseTable
        :columns="useTableColumns().value"
        :data="userList"
        :loading="loading"
        :pagination="pagination"
        :selectedRowKeys="selectedRowKeys"
        :enableStatusColumn="true"
        :loadError="loadError"
        :errorMessage="errorMessage"
        :emptyTextKey="'user.emptyData'"
        @selection-change="onSelectChange"
        @table-change="handleTableChange"
        @status-change="(id, status) => handleStatusChange(id, typeof status === 'boolean' ? (status ? 1 : 0) : status)"
        @retry="fetchUserList"
      >
        <template #action="{ record }">
          <a-button type="link" size="small" @click="handleEdit(record.id)">
            <template #icon><EditOutlined /></template>{{ $t('common.edit') }}
          </a-button>
          <a-button type="link" size="small" @click="handleAssignRoles(record as User)">
            <template #icon><UserSwitchOutlined /></template>{{ $t('user.assignRoles') }}
          </a-button>
          <a-button type="link" size="small" @click="handleResetPassword(record as User)">
            <template #icon><KeyOutlined /></template>{{ $t('user.resetPassword') }}
          </a-button>
          <a-button type="link" size="small" danger @click="handleDelete(record.id)">
            <template #icon><DeleteOutlined /></template>{{ $t('common.delete') }}
          </a-button>
        </template>
      </BaseTable>

      <!-- 用户表单弹窗 -->
      <BaseModal
        v-model:visible="formModalOpen"
        :title="formMode === 'add' ? $t('user.addUser') : $t('user.editUser')"
        :form-items="userFormItems"
        :rules="userRules"
        :record="formData"
        :loading="submitLoading"
        @submit="handleSubmit"
        @cancel="formModalOpen = false"
        class="common-modal-form"
        ref="formModalRef"
      />
            
      <!-- 重置密码弹窗 -->
      <BaseModal
        v-model:visible="passwordModalOpen"
        :title="$t('user.resetPassword')"
        :form-items="resetPasswordItems"
        :rules="resetPasswordRules"
        :record="passwordData"
        :loading="passwordSubmitLoading"
        @submit="handleSubmitResetPassword"
        @cancel="passwordModalOpen = false"
        class="common-modal-form"
      />

      <!-- 分配角色弹窗 -->
      <AssignRolesModal
        :open="roleModalOpen"
        @update:open="roleModalOpen = $event"
        :model-value="targetRoleIds"
        @update:model-value="targetRoleIds = $event"
        :role-list="roleListForTransfer"
        :loading="roleSubmitLoading"
        @submit="handleSubmitRoles"
        class="common-modal-form"
      />
    </a-card>
  </div>
</template>

<script lang="ts" setup>
import { ref, watch, computed, reactive } from 'vue'
import { EditOutlined, DeleteOutlined, UserSwitchOutlined, KeyOutlined } from '@ant-design/icons-vue'
import { useTableColumns } from './config/tableColumns'
import { useLeftButtons, useRightButtons } from './config/operationButtons'
import { useSearchItems } from './config/searchItems'
import useUserManagement from './hooks/useUserManagement'
import { useUserStore } from '@/stores/system/user'
import Operations from '@/components/common/Operations.vue'
import BaseTable from '@/components/common/BaseTable.vue'
import BaseSearch from '@/components/common/BaseSearch.vue'
import BaseModal from '@/components/common/BaseModal.vue'
import AssignRolesModal from './components/AssignRolesModal.vue'
import type { User } from '@/types/api/system/user'

// 从配置文件导入表单配置
import { useUserFormItems } from './config/userFormItems'
import { useUserFormRules, useResetPasswordRules } from './config/formRules'
import { useResetPasswordFormItems } from './config/resetPasswordFormItems'

// 组件名称
defineOptions({
  name: 'UserManagement'
})

// 获取用户Store
const userStore = useUserStore()

// 表单引用
const formModalRef = ref(null)

// 使用用户管理钩子
const {
  // 状态数据
  loading,
  submitLoading,
  roleSubmitLoading,
  passwordSubmitLoading,
  formModalOpen,
  roleModalOpen,
  passwordModalOpen,
  userList,
  deptTreeData,
  roleOptions,
  roleListForTransfer,
  targetRoleIds,
  selectedRowKeys,
  selectedCount,
  dateRange,
  pagination,
  queryParams,
  formData,
  formMode,
  passwordForm,
  loadError,
  errorMessage,
  
  // 表格交互方法
  onSelectChange,
  handleTableChange,
  
  // 搜索区域方法
  handleSearch,
  handleReset,
  handleDateRangeChange,
  
  // 表单操作方法
  handleAdd,
  handleEdit,
  handleSubmit,
  
  // 删除操作方法
  handleDelete,
  handleBatchDelete,
  
  // 状态管理方法
  handleStatusChange,
  
  // 特殊业务方法
  handleExport,
  handleAssignRoles,
  handleSubmitRoles,
  handleResetPassword,
  handleSubmitResetPassword,
  
  // 数据获取方法
  fetchUserList
} = useUserManagement()

// 使用搜索表单配置
const searchItems = useSearchItems([])

// 用户表单配置 - 使用Computed避免类型问题
const userFormItems = computed(() => {
  // 创建临时formMode对象以解决类型问题
  const mode = ref(formMode)
  return useUserFormItems(mode, deptTreeData, roleOptions).value
})

const userRules = computed(() => {
  // 创建临时formMode对象以解决类型问题
  const mode = ref(formMode)
  return useUserFormRules(mode).value
})

// 重置密码表单数据
const passwordData = reactive({
  newPassword: '',
  confirmPassword: ''
})

// 监听密码表单数据变化
watch(passwordForm, () => {
  passwordData.newPassword = passwordForm.newPassword
  passwordData.confirmPassword = passwordForm.confirmPassword
}, { deep: true, immediate: true })

// 重置密码表单配置
const resetPasswordItems = computed(() => {
  const targetUser = userList.value.find(user => user.id === userStore.currentId)
  return useResetPasswordFormItems(targetUser?.username).value
})

const resetPasswordRules = computed(() => {
  return useResetPasswordRules(passwordData).value
})

// 监听deptTreeData变化，更新searchItems
watch(() => deptTreeData.value, (newDeptTree) => {
  if (Array.isArray(newDeptTree)) {
    const deptItem = searchItems.value.find(item => item.field === 'deptId')
    if (deptItem) {
      deptItem.treeData = newDeptTree
    }
  }
}, { immediate: true })
</script>

<style lang="scss" scoped>
@import '@/assets/styles/views/common.scss';
</style> 